package com.mogician.feihualing.feihualing;

import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class PoemAdapter extends RecyclerView.Adapter<PoemAdapter.ViewHolder>
{
    private List<Poem> poemList;
    private String key;
    static class ViewHolder extends RecyclerView.ViewHolder
    {
        TextView sentence;
        TextView from;

        public ViewHolder(View view)
        {
            super(view);
            sentence = (TextView) view.findViewById(R.id.sentence);
            from = (TextView) view.findViewById(R.id.from);
        }
    }

    public PoemAdapter(List<Poem> poemList, String key)
    {
        this.poemList = poemList;
        this.key = key;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
    {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.poem_container, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position)
    {
        Poem poem = poemList.get(position);
        String content = poem.getContent();
        int index = 0;
        ArrayList<Integer> list = new ArrayList<>();
        while ((index = content.indexOf(key, index + key.length())) != -1)
            list.add(new Integer(index));
        SpannableString spannableString = new SpannableString(content);
        for(Integer tag : list)
        {
            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#f15b6c")),
                    tag.intValue(), tag.intValue() + key.length(),
                    Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        }
        viewHolder.sentence.setText(spannableString);
        viewHolder.from.setText("——" + poem.getPoet() + "《" + poem.getTitle() + "》");
    }

    @Override
    public int getItemCount()
    {
        return poemList.size();
    }

}
